#!/usr/bin/env python3
# HFT系统配置管理工具

import json
import os
import argparse
from getpass import getpass
import hashlib
from cryptography.fernet import Fernet

class HFTConfigManager:
    def __init__(self, config_dir='config'):
        self.config_dir = config_dir
        self.encryption_key = self._load_or_generate_key()
        self.cipher = Fernet(self.encryption_key)
        
    def _load_or_generate_key(self):
        """加载或生成加密密钥"""
        key_file = os.path.join(self.config_dir, '.config_key')
        if os.path.exists(key_file):
            with open(key_file, 'rb') as f:
                return f.read()
        else:
            key = Fernet.generate_key()
            with open(key_file, 'wb') as f:
                f.write(key)
            os.chmod(key_file, 0o600)  # 限制权限
            return key
    
    def encrypt_config(self, config):
        """加密敏感配置"""
        sensitive_fields = ['password', 'api_key', 'secret']
        for field in sensitive_fields:
            if field in config:
                config[field] = self.cipher.encrypt(config[field].encode()).decode()
        return config
    
    def decrypt_config(self, config):
        """解密敏感配置"""
        sensitive_fields = ['password', 'api_key', 'secret']
        for field in sensitive_fields:
            if field in config:
                config[field] = self.cipher.decrypt(config[field].encode()).decode()
        return config
    
    def create_config(self, template_name, output_name):
        """从模板创建新配置"""
        template_path = os.path.join(self.config_dir, f'{template_name}.example.json')
        output_path = os.path.join(self.config_dir, f'{output_name}.json')
        
        if not os.path.exists(template_path):
            raise FileNotFoundError(f'模板文件不存在: {template_path}')
            
        with open(template_path) as f:
            config = json.load(f)
            
        print(f"正在创建新配置: {output_name}")
        for key, value in config.items():
            if isinstance(value, str) and value.startswith('ENTER_'):
                prompt = value.replace('ENTER_', '')
                secret = key.lower() in ['password', 'api_key', 'secret']
                config[key] = getpass(prompt) if secret else input(prompt)
        
        config = self.encrypt_config(config)
        
        with open(output_path, 'w') as f:
            json.dump(config, f, indent=2)
            
        print(f"配置已保存到: {output_path}")
    
    def validate_config(self, config_name):
        """验证配置完整性"""
        config_path = os.path.join(self.config_dir, f'{config_name}.json')
        
        if not os.path.exists(config_path):
            raise FileNotFoundError(f'配置文件不存在: {config_path}')
            
        with open(config_path) as f:
            config = json.load(f)
            
        required_fields = {
            'system_config': ['broker_id', 'account', 'password'],
            'strategy_config': ['strategy_name', 'instruments'],
            'risk_config': ['max_position', 'max_loss']
        }
        
        config_type = None
        for t in required_fields:
            if t in config_name:
                config_type = t
                break
                
        if not config_type:
            return True  # 无法识别的配置类型，跳过验证
            
        missing = []
        for field in required_fields[config_type]:
            if field not in config:
                missing.append(field)
                
        if missing:
            raise ValueError(f'缺少必要字段: {", ".join(missing)}')
            
        print(f"配置验证通过: {config_name}")
        return True
    
    def list_configs(self):
        """列出所有配置文件"""
        configs = []
        for f in os.listdir(self.config_dir):
            if f.endswith('.json') and not f.endswith('.example.json'):
                configs.append(f[:-5])  # 移除.json扩展名
        return configs

def main():
    parser = argparse.ArgumentParser(description='HFT系统配置管理工具')
    subparsers = parser.add_subparsers(dest='command', required=True)
    
    # 创建配置命令
    create_parser = subparsers.add_parser('create', help='从模板创建新配置')
    create_parser.add_argument('template', help='模板名称(不带扩展名)')
    create_parser.add_argument('output', help='输出配置名称(不带扩展名)')
    
    # 验证配置命令
    validate_parser = subparsers.add_parser('validate', help='验证配置完整性')
    validate_parser.add_argument('config', help='配置名称(不带扩展名)')
    
    # 列出配置命令
    subparsers.add_parser('list', help='列出所有配置文件')
    
    args = parser.parse_args()
    manager = HFTConfigManager()
    
    try:
        if args.command == 'create':
            manager.create_config(args.template, args.output)
        elif args.command == 'validate':
            manager.validate_config(args.config)
        elif args.command == 'list':
            print("可用配置文件:")
            for config in manager.list_configs():
                print(f" - {config}")
    except Exception as e:
        print(f"错误: {e}")
        exit(1)

if __name__ == '__main__':
    main()